package com.shenghui.enterprise.utils;

import com.shenghui.enterprise.base.entity.BaseUser;
import com.shenghui.enterprise.contant.ConstantInfo;
import com.shenghui.enterprise.enterprise.entity.EntBasicInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class UserUtil {
	@Autowired
	private HttpServletRequest request;

	public void setLoginUser(HttpServletRequest request, BaseUser user) {
		request.getSession().setAttribute(ConstantInfo.ADMIN_LOGIN_USER, user);
		request.getSession().setAttribute(ConstantInfo.ADMIN_LOGIN_USER_ID, user.getUserId());
	}

	public BaseUser getLoginUser() {
		if (request == null) {
			return null;
		}
		return (BaseUser) request.getSession().getAttribute(ConstantInfo.ADMIN_LOGIN_USER);
	}

	public void setFrontLoginUser(HttpServletRequest request, EntBasicInfo entBasicInfo) {
		request.getSession().setAttribute(ConstantInfo.FRONT_LOGIN_USER, entBasicInfo);
		request.getSession().setAttribute(ConstantInfo.FRONT_LOGIN_USER_ID, entBasicInfo.getId());
	}

	public EntBasicInfo getFrontLoginUser() {
		if (request == null) {
			return null;
		}
		return (EntBasicInfo) request.getSession().getAttribute(ConstantInfo.FRONT_LOGIN_USER);
	}

	public String getUserName() {
		BaseUser baseUser = (BaseUser) request.getSession().getAttribute(ConstantInfo.ADMIN_LOGIN_USER);
		if (!GeneralUtil.isNull(baseUser) && !GeneralUtil.isNull(baseUser.getAccount())) {
			return baseUser.getAccount();
		}
		return null;
	}

	public String getRealName() {
		BaseUser baseUser = (BaseUser) request.getSession().getAttribute(ConstantInfo.ADMIN_LOGIN_USER);
		if (!GeneralUtil.isNull(baseUser) && !GeneralUtil.isNull(baseUser.getAccount())) {
			return baseUser.getName();
		}
		return null;
	}

	public String getUserId() {
		try {
			if (request == null) {
				return "";
			}
			if (GeneralUtil.isNotNull(request.getSession().getAttribute(ConstantInfo.ADMIN_LOGIN_USER_ID))) {
				return request.getSession().getAttribute(ConstantInfo.ADMIN_LOGIN_USER_ID).toString();
			}
			return "";
		} catch (Exception e) {
			return "";
		}
	}

	public String getFrontUserId() {
		try {
			if (request == null) {
				return "";
			}
			if (GeneralUtil.isNotNull(request.getSession().getAttribute(ConstantInfo.FRONT_LOGIN_USER))) {
				return request.getSession().getAttribute(ConstantInfo.FRONT_LOGIN_USER_ID).toString();
			}
			return "";
		} catch (Exception e) {
			return "";
		}
	}

	public void logout(HttpServletRequest request) {
		request.getSession().removeAttribute(ConstantInfo.ADMIN_LOGIN_USER);
		request.getSession().removeAttribute(ConstantInfo.ADMIN_LOGIN_USER_ID);
	}

	public void frontLogout(HttpServletRequest request) {
		request.getSession().removeAttribute(ConstantInfo.FRONT_LOGIN_USER);
		request.getSession().removeAttribute(ConstantInfo.FRONT_LOGIN_USER_ID);
	}
}
